import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { pinia_global_state } from '@/state/state.ts'

const routers: RouteRecordRaw[] = [
  { name: 'login', path: '/login', component: () => import('@/pages/Login.vue'), meta: { title: '登录 - 灰灰' } },
  {
    path: '/',
    component: () => import('@/pages/Home.vue'),
    meta: { title: '' },
    children: [
      { name: 'dashboard', path: '/dashboard', component: () => import('@/pages/home/Dashboard.vue'), meta: { title: '仪表板' } },
      { name: 'websites', path: '/websites', component: () => import('@/pages/home/Websites.vue'), meta: { title: '站点配置' } },
      { name: 'applications', path: '/applications', component: () => import('@/pages/home/Applications.vue'), meta: { title: '应用列表' } },
      { name: 'settings', path: '/settings', component: () => import('@/pages/home/Settings.vue'), meta: { title: '系统设置' } },
      {
        name: 'toolbox',
        path: '/toolbox',
        component: () => import('@/pages/home/Toolbox.vue'),
        meta: { title: '工具箱' },
        children: [
          { name: 'toolbox-index', path: '/toolbox/index', component: () => import('@/pages/home/toolbox/Index.vue'), meta: { title: '列表 - 工具箱' } },
          { name: 'toolbox-resources', path: '/toolbox/resources', component: () => import('@/pages/home/toolbox/Resources.vue'), meta: { title: '资源管理器 - 工具箱' } },
          { name: 'toolbox-downloader', path: '/toolbox/downloader', component: () => import('@/pages/home/toolbox/Downloader.vue'), meta: { title: '文件下载器 - 工具箱' } },
        ]
      },
      { name: 'application-v2ray-configuration', path: '/application/v2ray-configuration', component: () => import('@/pages/home/application/ApplicationV2rayConfiguration.vue'), meta: { title: 'V2ray应用配置 - 应用管理' } }
    ]
  }
]
export const router = createRouter({ history: createWebHistory(), routes: routers })
router.beforeEach((to, _, next) => {
  const state = pinia_global_state()
  if ('login' !== to.name && '' === state.token) {
    next({ name: 'login' })

    return
  }

  document.title = to.meta['title'] as string

  next()
})
